<template>
  <div class="courseOutline bg-fff">
    <div ref="mindMapContainer" class="mind-map-container"></div>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted, onBeforeUnmount, watch, nextTick } from 'vue'
import MindElixir, { type MindElixirInstance } from 'mind-elixir'

const props = defineProps<{
  data: any
}>()

const mindMapContainer = ref<HTMLElement | null>(null)
let mindMapInstance: MindElixirInstance | null = null

const initMindMap = () => {
  if (!mindMapContainer.value) {
    console.error('Container is missing')
    return
  }

  const observer = new ResizeObserver((entries) => {
    for (const entry of entries) {
      const { width, height } = entry.contentRect
      if (width > 0 && height > 0) {
        // 确保容器尺寸有效后再初始化 MindElixir
        observer.disconnect() // 停止监听
        initMindElixir()
      }
    }
  })

  observer.observe(mindMapContainer.value)
}
const collapseAllNodes = (node: any) => {
  node.expanded = false
  if (node.children && node.children.length) {
    node.children.forEach(collapseAllNodes)
  }
}
const initMindElixir = () => {
  try {
    if (!props.data || !props.data.nodeData) {
      throw new Error('Invalid data')
    }
    // 统一设置初始为折叠
    collapseAllNodes(props.data.nodeData)

    mindMapInstance = new MindElixir({
      el: mindMapContainer.value as any,
      direction: MindElixir.SIDE, // 设置思维导图的方向

      draggable: false,
      editable: false
    })

    mindMapInstance.init(props.data)

    // 监听节点选中事件
    mindMapInstance.bus.addListener('selectNode', (node: any) => {
      console.log('选中节点:', node)
      if (node.url) {
        window.open(node.url, '_blank')
      }
    })
  } catch (error) {
    console.error('报错', error)
    if (error instanceof Error) {
      console.error('Error message:', error.message)
      console.error('Error stack:', error.stack)
    }
  }
}

watch(
  () => props.data,
  (newData) => {
    if (newData && mindMapContainer.value) {
      initMindMap()
    }
  },
  { immediate: true }
)

onMounted(async () => {
  await nextTick(() => {
    initMindMap()
  })
})

onBeforeUnmount(() => {
  if (mindMapInstance) {
    mindMapInstance.destroy()
    mindMapInstance = null
  }
})
</script>

<style scoped lang="scss">
.courseOutline {
  padding: 20px;
  box-sizing: border-box;
  border-radius: 12px;
  margin-top: 24px;
}
.mind-map-container {
  width: 100%;
  height: 600px;
}
</style>
